package models

import (
	"net/url"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

func init() {
	user := beego.AppConfig.String("dbuser")
	password := beego.AppConfig.String("dbpass")
	host := beego.AppConfig.String("dbhost")
	port := beego.AppConfig.String("dbport")
	dbname := beego.AppConfig.String("dbname")
	timezone := beego.AppConfig.String("dbtimezone")
	if port == "" {
		port = "3306"
	}
	if timezone == "" {
		timezone = "UTC"
	}
	// %s:%s@tcp(%s:%s)/%s?charset=utf8&loc=%s
	dsn := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + dbname + "?charset=utf8&loc=" + url.QueryEscape(timezone)

	orm.RegisterDriver("mysql", orm.DRMySQL)
	orm.RegisterDataBase("default", "mysql", dsn)

	maxIdleConns, err := beego.AppConfig.Int("dbMaxIdleConns")
	if err != nil {
		maxIdleConns = 30
	}
	maxOpenConns, err := beego.AppConfig.Int("dbMaxOpenConns")
	if err != nil {
		maxOpenConns = 30
	}

	orm.SetMaxIdleConns("default", maxIdleConns)
	orm.SetMaxOpenConns("default", maxOpenConns)

	orm.Debug = true
}
